package com.dpiinc.TechPage.user.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.pdf.PdfDocument;
import android.net.Uri;
import android.text.Layout;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;

import com.dpiinc.TechPage.AIWriteApplication;
import com.dpiinc.TechPage.R;
import com.dpiinc.TechPage.room.RoomAiWriterDatabase;
import com.dpiinc.TechPage.room.bean.UserEntity;
import com.dpiinc.TechPage.widget.CircleImageView;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import com.tqltech.tqlpencomm.util.BLEFileUtil;

import org.jetbrains.annotations.NotNull;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.itextpdf.text.PageSize.A4;

/**
 * Created by hu489_000 on 2018-07-14.
 */

public class ViewToBitmapUtil {

    public static final String TAG = "ViewToBitmapUtil";
//    public static final String share_dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/aiwirte/share/";
    public static final String share_dir = AIWriteApplication.instance.getFilesDir() + "/aiwirte/share/";
    public static final String pdf_dir = AIWriteApplication.instance.getFilesDir() + "/aiwirte/pdf/";
    public static final String txt_dir = AIWriteApplication.instance.getFilesDir() + "/aiwirte/txt/";
    public static final String share_dir_save = AIWriteApplication.instance.getFilesDir() + "/aiwirte/";
    public static final String source_file = share_dir + "source.jpg";//原始图片，用于保存图片到图库和保存pdf
    public static final String share_file = share_dir + "share.jpg";//添加了头尾的图片，用于分享
    public static final String share_txt = txt_dir + "share.txt";//添加了头尾的图片，用于分享

    public static final int MAX_IMAGES = 10;//最多保存10页用于保存和分享
    public static String pdf;
    public static String mContent;


    private static void saveBitmap(Bitmap bitmap, String fileName) {
        File dir = new File(share_dir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(fileName);

        if (bitmap != null) {
            try {
                FileOutputStream outputStream = null;
                try {
                    outputStream = new FileOutputStream(file); //here is set your file path where you want to save or also here you can set file object directly

                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); // bitmap is your Bitmap instance, if you want to compress it you can compress reduce percentage
                    // PNG is a lossless format, the compression factor (100) is ignored
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (outputStream != null) {
                            outputStream.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void generateAllBitmap(Context context, @NotNull ArrayList<String> bitmapPathList) {

        File file = new File(source_file);
        if (file.exists()) {
            file.delete();
        }

        File sharefile = new File(share_file);
        if (sharefile.exists()) {
            sharefile.delete();
        }

        Log.d(TAG, "bitmapPathList" + bitmapPathList.size());
        Bitmap bitmap = null;
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        if (bitmapPathList != null && bitmapPathList.size() > 0) {
            ArrayList<Bitmap> bsList = new ArrayList<Bitmap>();
            for (int i = 0; i < bitmapPathList.size(); i++) {
                if(i >= MAX_IMAGES){
                    break;
                }
                Bitmap iBitmap = BitmapFactory.decodeFile(bitmapPathList.get(i), bmOptions);
                bsList.add(iBitmap);
            }
            bitmap = combineImageIntoOne(bsList);
            bitmap = changeBg(bitmap);
            saveBitmap(bitmap, source_file);

            //生成有头尾的图片用于分享
            createShareBitmap(context, bitmap);

            if (!bitmap.isRecycled()) {
                bitmap.recycle();
                bitmap = null;
            }
        }
    }

    private static void createShareBitmap(Context context, Bitmap bit) {
        int headHeight = (int)context.getResources().getDimension(R.dimen.dp106);
        int bottomHeight = (int)context.getResources().getDimension(R.dimen.dp68);
        int height = bit.getHeight() + headHeight + +bottomHeight;
        Bitmap finalShare = Bitmap.createBitmap(bit.getWidth(), height, Bitmap.Config.ARGB_8888);

        LayoutInflater inflater = LayoutInflater.from(context);

        View headView = inflater.inflate(R.layout.share_head, null);
        headView.setMinimumWidth(bit.getWidth());
        intHeadView(context, headView);
        Bitmap headBitmap = loadBitmapFromView(headView, bit.getWidth(), headHeight);
        Canvas canvas = new Canvas(finalShare);
        canvas.drawBitmap(headBitmap, 0, 0, null);
        canvas.drawBitmap(bit, 0, headHeight, null);

        View bottomView = inflater.inflate(R.layout.share_bottom, null);
        Bitmap bottomBitmap = loadBitmapFromView(bottomView, bit.getWidth(), bottomHeight);
        canvas.drawBitmap(bottomBitmap, 0, bit.getHeight() + headHeight, null);

        Bitmap codeBitmap = BitmapFactory.decodeResource(context.getResources(),R.drawable.code);
        int codeBitmapWidth = codeBitmap.getWidth();
        int codeBitmapHeight = codeBitmap.getHeight();
        float scaleWidth = (context.getResources().getDimension(R.dimen.dp40)) / codeBitmapWidth;
        float scaleHeight = (context.getResources().getDimension(R.dimen.dp40)) / codeBitmapHeight;
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap newCodeBitmap = Bitmap.createBitmap(codeBitmap,0,0,codeBitmapWidth,codeBitmapHeight,matrix,true);
        canvas.drawBitmap(newCodeBitmap, bit.getWidth()-(int)context.getResources().getDimension(R.dimen.dp54), bit.getHeight() + headHeight + (int)context.getResources().getDimension(R.dimen.dp14), null);

        saveBitmap(finalShare, share_file);
    }

    public static Bitmap createVideoBottomBitmap(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        int width =  (int)context.getResources().getDimension(R.dimen.dp400);
        int bottomHeight = (int)context.getResources().getDimension(R.dimen.dp40);
        LayoutInflater inflater = LayoutInflater.from(context);
        View bottomView = inflater.inflate(R.layout.share_small_bottom, null);
        return loadBitmapFromView(bottomView, width, bottomHeight);
    }


    public static Bitmap loadBitmapFromView(View v, int width, int height) {
        v.measure(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        v.layout(0, 0, width, height);
        v.draw(c);
        return b;
    }

    private static Bitmap changeBg(Bitmap bitmap) {

        Bitmap bg = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bg);
        canvas.drawColor(Color.WHITE);
        canvas.drawBitmap(bitmap, 0, 0, null);
        return bg;
    }

    private static Bitmap combineImageIntoOne(ArrayList<Bitmap> bitmap) {
        int w = 0, h = 0;
        w = bitmap.get(0).getWidth();
        for (int i = 0; i < bitmap.size(); i++) {
            if (i < bitmap.size() - 1) {
                w = bitmap.get(i).getWidth() > bitmap.get(i + 1).getWidth() ? bitmap.get(i).getWidth() : bitmap.get(i + 1).getWidth();
            }
            h += bitmap.get(i).getHeight();
        }

        Bitmap temp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(temp);
        int top = 0;
        for (int i = 0; i < bitmap.size(); i++) {
            Log.d(TAG, "Combine: " + i + "/" + bitmap.size() + 1);

            top = (i == 0 ? 0 : top + bitmap.get(i).getHeight());
            canvas.drawBitmap(bitmap.get(i), 0f, top, null);
        }
        return temp;
    }


    public static boolean saveBitmapToGallery(Context context) {
        File foder = new File(share_dir_save);
        if (!foder.exists()) {
            foder.mkdirs();
        }
        File myCaptureFile = new File(foder, "TechPage_" + System.currentTimeMillis() + ".jpg");

        boolean issuccess = CopySdcardFile(share_file, myCaptureFile.getAbsolutePath());

        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(myCaptureFile);
        intent.setData(uri);
        context.sendBroadcast(intent);
        return issuccess;
    }


    public static boolean CopySdcardFile(String fromFile, String toFile) {

        try {
            InputStream fosfrom = new FileInputStream(fromFile);
            OutputStream fosto = new FileOutputStream(toFile);
            byte bt[] = new byte[1024];
            int c;
            while ((c = fosfrom.read(bt)) > 0) {
                fosto.write(bt, 0, c);
            }
            fosfrom.close();
            fosto.close();
            return true;

        } catch (Exception ex) {
            return false;
        }

    }

    /**
     * 向文件中写入数据
     *
     * @param content  要写入的内容
     * @return 写入成功返回true， 写入失败返回false
     * @throws IOException
     */
    public static boolean saveToTxt(String content) throws IOException {
        mContent = content;
        File txtOld = new File(share_txt);
        if (txtOld.exists()) {
            txtOld.delete();
        }
        File dir = new File(txt_dir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        FileWriter fileWriter = null;
        try {
            BLEFileUtil.createFile(share_txt);
            File tempFile = new File(share_txt);
            if (!tempFile.exists()) {
                if (!tempFile.mkdirs()) {
                    return false;
                }
            }
            fileWriter = new FileWriter(share_txt, true);
            fileWriter.write(content);
            fileWriter.flush();
            return true;
        } finally {
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static boolean saveToPDF(Context context, ArrayList<String> list) {
        if (list == null && list.size() == 0) {
            return false;
        }
        Document document = new Document(A4, 50, 50, 30, 20);
//        String pdf = pdf_dir + context.getString(R.string.app_name)+"_" + System.currentTimeMillis() + ".pdf";
        pdf = pdf_dir +  shareTitle + ".pdf";
        File fdf_file = new File(pdf);
        try {

            File dir = new File(pdf_dir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdf));
            document.open();
            if (list.size() == 0) {
                document.add(new Paragraph("aiWrite"));
                document.newPage();
            }
            for (String str : list) {
                //Add Image
                Log.e(TAG, "保存PDF内容Document===>" + str);
                Image image = Image.getInstance(str);
                float scaler = ((document.getPageSize().getWidth() - document.leftMargin()
                        - document.rightMargin() - 0) / image.getWidth()) * 100; // 0 means you have no indentation. If you have any, change it.
                image.scalePercent(scaler);
                image.setAlignment(Image.ALIGN_CENTER | Image.ALIGN_TOP);
                //Add to document
                document.add(image);
            }

            document.close();
            writer.close();


            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(fdf_file);
            intent.setData(uri);
            context.sendBroadcast(intent);
        } catch (Exception e) {
            Log.e(TAG, "报错====>" +e.getMessage());
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static void saveToNewPDF(String hdrText) {
        try {
            //   Document document = new Document(A4, 50, 50, 30, 20);
//        String pdf = pdf_dir + context.getString(R.string.app_name)+"_" + System.currentTimeMillis() + ".pdf";

            File file = new File(pdf_dir);
            if (!file.exists()) {
                file.mkdirs();
            }
            PdfDocument document = new PdfDocument();
            /***宽 高 页数******/
            PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(612, 792, 1).create();
            PdfDocument.Page page = document.startPage(pageInfo);
            TextPaint textPaint = new TextPaint();
            textPaint.setColor(Color.BLACK);
            textPaint.setTextSize(16);
            textPaint.setTextAlign(Paint.Align.LEFT);

            Typeface textTypeface = Typeface.create(Typeface.MONOSPACE, Typeface.NORMAL);
            textPaint.setTypeface(textTypeface);

            StaticLayout mTextLayout = new StaticLayout(hdrText, textPaint, page.getCanvas().getWidth(),
                    Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);

            mTextLayout.draw(page.getCanvas());
            document.finishPage(page);

           // pdf = pdf_dir +  "pdf_android.pdf";
            pdf = pdf_dir +  shareTitle + ".pdf";
            File file1 = new File(pdf);
          //  File file1 = new File(file, "pdf_android.pdf");
            try {
                FileOutputStream mFileOutStream = new FileOutputStream(file1);

                document.writeTo(mFileOutStream);
                mFileOutStream.flush();
                mFileOutStream.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static void intHeadView(Context context, View headView) {
        TextView user_nickname = (TextView) headView.findViewById(R.id.user_nickname);
        CircleImageView imageView =(CircleImageView)headView.findViewById(R.id.user_imageView);
        TextView title =  (TextView) headView.findViewById(R.id.title);
        title.setText(shareTitle);
        TextView time = (TextView) headView.findViewById(R.id.time);
        time.setText(shareTime);
        RoomAiWriterDatabase db = RoomAiWriterDatabase.getInstance(context);
        List<UserEntity> list =  db.userDao().getAll();
        if(list !=null && list.size()>0){
            UserEntity user = list.get(0);

            Log.d(TAG,"user = " + user);
            if(user.getNickname()!= null) {
                user_nickname.setText(user.getNickname());
            }
            showImage(imageView, user.getNickImage());
        }
    }


    private static void showImage(CircleImageView imageView, String nickImage) {
        if(TextUtils.isEmpty(nickImage)){
            return;
        }
        //利用Base64将字符串转换为ByteArrayInputStream
        byte[] byteArray= Base64.decode(nickImage, Base64.DEFAULT);
        if(byteArray.length==0){
        }else{
            ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(byteArray);

            //利用ByteArrayInputStream生成Bitmap
            Bitmap bitmap= BitmapFactory.decodeStream(byteArrayInputStream);
            imageView.setImageBitmap(bitmap);
        }
    }

    private static String shareTime;
    private static String shareTitle;

    public static void setShareTime(long currentTimeMillis) {
        @SuppressLint("SimpleDateFormat") SimpleDateFormat format=new SimpleDateFormat(AIWriteApplication.Companion.instance().getResources().getString(R.string.share_time_patten));

        Date d1=new Date(currentTimeMillis);
        shareTime=format.format(d1);
    }

    public static void setShareTitle(String shareTitle) {
        ViewToBitmapUtil.shareTitle = shareTitle;
    }
}
